package com.flyduck.vueshop.order.h5.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.vueshop.common.mybatis.utils.PageUtils;
import com.flyduck.vueshop.common.sotoken.utils.StpUserUtil;
import com.flyduck.vueshop.order.constant.OrderConstant;
import com.flyduck.vueshop.order.entity.AppOrder;
import com.flyduck.vueshop.order.entity.AppOrderItem;
import com.flyduck.vueshop.order.h5.service.H5OrderItemService;
import com.flyduck.vueshop.order.h5.vo.H5OrderItemRespVO;
import com.flyduck.vueshop.order.mapper.AppOrderItemMapper;
import com.flyduck.vueshop.order.mapper.AppOrderMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * H5OrderItemServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-07-23
 */
@Service
public class H5OrderItemServiceImpl implements H5OrderItemService {

    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private AppOrderItemMapper appOrderItemMapper;

    /**
     *
     * @param page
     * @param status 0:未评论 1:已评论
     * @return
     */
    @Override
    public Page<H5OrderItemRespVO> getOrderItemPageByStatus(Page page, Integer status) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        //1、获取待评论的订单列表，就是已完成的订单列表
        List<Object> completedOrderIds = appOrderMapper.selectObjs(
                new LambdaQueryWrapper<AppOrder>()
                        .eq(AppOrder::getUserId, userId)
                        .eq(AppOrder::getOrderStatus, OrderConstant.OrderStatus.COMPLETED.getCode())
                        .select(AppOrder::getId)
        );


        //2、再获取已完成的订单列表的待评论的商品
        Page<AppOrderItem> appOrderItemPage = new Page<>();
        if(CollectionUtil.isNotEmpty(completedOrderIds)){
            appOrderItemPage = appOrderItemMapper.selectPage(
                    page,
                    new LambdaQueryWrapper<AppOrderItem>()
                            .in(AppOrderItem::getOrderId, completedOrderIds)
                            .isNull(status == 0, AppOrderItem::getCommentId)
                            .isNotNull(status == 1, AppOrderItem::getCommentId)
                            .orderByDesc(AppOrderItem::getCreated)
            );
        }
        return PageUtils.convert(appOrderItemPage, H5OrderItemRespVO.class);
    }
}
